package com.nowcoder.community.actuator;

import com.nowcoder.community.util.CommunityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 监控数据库 端点
 * @author 花木凋零成兰
 * @date 2024/4/2 23:03
 */
@Component
@Endpoint(id = "database")
@Slf4j(topic = "DatabaseEndpoint.class")
public class DatabaseEndpoint {

    @Resource
    private DataSource dataSource;

    @ReadOperation  // 声明是GET请求访问
    public String checkConnection() {
        try (
                Connection connection = dataSource.getConnection()
        ) {
            return CommunityUtil.getJSONString(0, "获取连接成功!");
        } catch (SQLException e) {
            log.error("获取数据库连接失败：{}", e.getMessage());
            return CommunityUtil.getJSONString(1, "获取连接失败!");
        }
    }

}
